<template>
  <t-dialog :visible="visible" attach="#app" header="修改学生信息" :confirm-btn="{ content: '修改' }" @confirm="submit" @close="closeDialog">
    <t-form :data="form" :rule="ruleForm" ref="dataForm">
      <t-form-item label="学生名称">
        <t-input readonly v-model="form.username" />
      </t-form-item>
      <t-form-item label="班级" name="class_id">
        <t-select v-model="form.class_id" class="demo-select-base">
          <t-option v-for="(item, index) in classOptions" :key="index" :value="item.value" :label="item.label">
            {{ item.label }}
          </t-option>
        </t-select>
      </t-form-item>
      <t-form-item label="类别">
        <t-select v-model="form.type">
          <t-option v-for="(item, index) in typeOptions" :key="index" :value="item.value" :label="item.label">
            {{ item.label }}
          </t-option>
        </t-select>
      </t-form-item>
    </t-form>
  </t-dialog>
</template>
<script setup lang="ts">
import {onMounted, ref} from "vue";
import {queryClass} from "../api/Class";
import {updateStudent} from "../api/Student";
import {MessagePlugin} from "tdesign-vue-next";
//弹框状态
const visible =ref<boolean>(false);
// 父子通信
const emit = defineEmits(['callback']);
// 表单信息
interface dataType {
  id: string | number;
  user_id: string | number;
  class_id: string | number;
  type: number;
  username: string;
}
const form = ref<dataType>({
  id: '',
  user_id: '',
  class_id: '',
  type: 0,
  username: '',
})
const typeOptions = ref( [
  { label: '普通学生', value: 0 },
  { label: '班级委员', value: 1 },
  { label: '副班长', value: 2 },
  { label: '班长', value: 3 },
],)
// 校验规则
const ruleForm = ref({
  class_id: [{ required: true, message: '请选择班级' }],
})
// 班级信息
interface classOptionsType {
  label: string;
  value: number;
}
const classOptions = ref<Array<classOptionsType>>([]);
// 打开弹框方法
const open = (data) => {
  form.value.class_id = data.class_id;
  form.value.username = data.username;
  form.value.id = data.id;
  form.value.user_id = data.user_id;
  form.value.type = data.type;
  visible.value = true;
}
// 修改学生
const submit = async () => {
  const result = await updateStudent(form.value);
  if(result) {
    MessagePlugin.success(result.message);
    visible.value = false;
    emit('callback');
  }
}
// 请求班级列表API
const queryClassType = async ():Promise<void> => {
  const classTypes = await queryClass();
  interface dataType {
    classname: string;
    id: number;
    create_time: string;
    update_time: string;
  }
  classTypes.data.forEach((item:dataType, i) => {
    classOptions.value.push({
      label: item.classname,
      value: item.id
    })
  });
}
// 关闭弹框
const closeDialog = () => {
  emit('callback');
  visible.value = false;
}
onMounted(()=> {
  queryClassType();
})
defineExpose({open})
</script>
<style lang="less">

</style>
